#!/usr/bin/python
#coding:utf-8

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import time
import sys

def insert_dic(res, tid, name, key_val):
    trans_name={
        "Developer(s)":"info_dever",\
        "Stable release":"info_stableVer",\
        "Written in":"info_codeLangs",\
        "Operating system":"info_os",\
        "Type":"info_type",\
        "License":"info_license",\
        "Initial release":"info_initVer",\
        "Development status":"info_devStat"}
    if name in trans_name.keys():
        res.append({'tid':tid, 'key_name':trans_name[name], 'key_val':key_val})

def get_wiki(tid, url):
    # driver = webdriver.Firefox()
    driver = webdriver.PhantomJS()
    # driver = webdriver.PhantomJS(executable_path="/home/gtmer/spider/phantomjs-2.1.1-linux-x86_64/bin/phantomjs")

    # tid = sys.argv[1]
    # url = sys.argv[2]
    # url = 'https://en.wikipedia.org/wiki/Apache_Kafka'

    driver.get(url)
    time.sleep(6)

    # time.sleep(10)
    # try:
    #     element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, 'lbPagerTitle')))
    # finally:
    # time.sleep(5)
    #只能找到element，不能定位到text()[2]
    # try:
    #     res = driver.find_element_by_xpath('/html/body/div[3]/div[3]/div[4]/div/table/tbody/tr[7]/th/a').text
    # except:
    #     #如果找不到就报错，此时数值为0
    #     res = ''
    # else:
    #     print res


    table = driver.find_element_by_xpath('//*[@class="infobox vevent"]')
    trs = table.find_elements_by_xpath('./tbody/tr')
    length = len(trs)
    # print length
    res = []
    for i in range(0, length):
        try:
            trs[i].find_element_by_xpath('./th')
        except:
            continue
        else:
            name = trs[i].find_element_by_xpath('./th').text
            key_val = trs[i].find_element_by_xpath('./td').text
            insert_dic(res, tid, name, key_val)

    # for tr in trs:
    #     tr.find_element_by_xpath('./th')
        

    # info_os = driver.find_element_by_xpath('//*[@title="Operating system"]').text
    # info_dever = 


    # finally:
        # outdic = {
        #     '51cto_num': num
        # }
        # outli = ['51cto_num', num, driver.current_url]
        # csvout.list2csv(outli)
        # print(outli)
    driver.close()
    print res

    # if res is None:
    #     num = 0
    # else:
    #     num = filter(lambda x: x.isdigit(), res)


    